package com.amado.course50java8;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java810StreamReduce {

    public static void main(String[] args) {
        one();
    }

    public static void one() {
        Stream<Integer> s = Stream.of(1, 2, 3, 4, 5, 6);

        /**
         * 求和，也可以写成Lambda语法：
         * Integer sum = s.reduce((a, b) -> a + b).get();
         */
        Integer sum = s.reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer integer, Integer integer2) {
                return integer + integer2;
            }
        }).get();

        s = Stream.of(1, 2, 3, 4, 5, 6);
        /**
         * 求最大值，也可以写成Lambda语法：
         * Integer max = s.reduce((a, b) -> a >= b ? a : b).get();
         */
        Integer max = s.reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer integer, Integer integer2) {
                return integer >= integer2 ? integer : integer2;
            }
        }).get();
        BigDecimal ss = Stream.of(new BigDecimal("2"),BigDecimal.ONE).reduce(new BigDecimal("2"),new BinaryOperator<BigDecimal>(){
            @Override
            public BigDecimal apply(BigDecimal bigDecimal, BigDecimal bigDecimal2) {
                return bigDecimal.add(bigDecimal2);
            }
        });
        System.out.println("ss = "+ss);
        System.out.println(sum);
        System.out.println(max);

        System.out.println(Stream.of(new BigDecimal("2"),BigDecimal.ONE).reduce(BigDecimal::add).get());
        //第二个参数，相当于初始化参数
        System.out.println(Arrays.asList(new BigDecimal("2"),BigDecimal.ONE,null).stream().map(e->e==null?BigDecimal.ZERO:e).reduce(BigDecimal.ZERO,BigDecimal::add));
    }

}
